package com.example.demo.util;

/**
 * Created with IntelliJ IDEA.
 * User:xieChao
 * Date:2022/12/29 21:29
 */

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import org.springframework.util.StringUtils;

/**
 * 密码工具类
 * 1.加密（加盐）
 * 2.解密
 */
public class PasswordUtil {
    public static String encrypt(String password) {
        //1.随机盐值生成
         String salt = IdUtil.simpleUUID();
         //2.密码(md5(随机盐值+密码))
        String finalPassword = SecureUtil.md5(salt+password);
         return salt + "$" + finalPassword;
    }

    /**
     * 解密
     * @param password  要验证的密码(未加密)
     * @param securePassword 数据库中的加盐密码
     * @return
     */
    public static boolean decrypt(String password,String securePassword){
        boolean result = false;
        if(StringUtils.hasLength(password) && StringUtils.hasLength(securePassword)){
            if(securePassword.length() == 65 && securePassword.contains("$")){
                String[] securePasswordArr = securePassword.split("\\$");
                //1.盐值
                String salt = securePasswordArr[0];
                String finalPassword = securePasswordArr[1];
                //2.对比
                password = SecureUtil.md5(salt + password);
                if(finalPassword.equals(password)){
                    result = true;
                }
            }
        }
        return result;
    }

    public static void main(String[] args) {
        String password = "admin";
        String dbPassword = PasswordUtil.encrypt(password);
        boolean result = PasswordUtil.decrypt("admin", dbPassword);
        System.out.println("对比结果：" + result);
    }
}
